package com.konsung.ksdc.manager.addr;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.AddrInfoBean;
import com.konsung.ksdc.bean.AddrUltimateBean;
import com.konsung.ksdc.bean.netbean.AddrInfoNetBean;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.PreferenceUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.common.widget.OnMultiClickListener;
import com.konsung.ksdc.common.widget.WaitingDialog;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.manager.appmain.BaseActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/5/13 0013.
 */
public class CreateAddrActivity extends BaseActivity {
    public static final String DISTRICT_DATA = "district_data";
    public static final String ADDR_JSON = "addr.json";

    @Bind(R.id.rl_back)
    RelativeLayout rlBack;
    @Bind(R.id.tab_tv_title)
    TextView tabTvTitle;
    @Bind(R.id.tv_save)
    TextView tvSave;
    @Bind(R.id.rl_title_container)
    RelativeLayout rlTitleContainer;
    @Bind(R.id.et_receiver)
    EditText etReceiver;
    @Bind(R.id.et_phone)
    EditText etPhone;
    @Bind(R.id.et_surplus_addr)
    EditText etSurplusAddr;
    @Bind(R.id.cb_default)
    CheckBox cbDefault;
    @Bind(R.id.ll_district_container)
    LinearLayout llDistrictContainer;
    @Bind(R.id.tv_district_name)
    TextView tvDistrictName;
    @Bind(R.id.et_postcode)
    EditText etPostcode;
    private boolean isDefault;
    private int position; // 修改的数据的位置
    private ArrayList<AddrUltimateBean> districtDatas;
    private String districtName;

    public static final String DISTRICT_NAME = "district_name";
    private String receiver;
    private String phone;
    private String districtName1;
    private String surplusAddr;

    public static final String EDIT_ADDR_TYPE = "edit_addr_type";
    public static final int TYPE_CREAT = 10010;
    public static final int TYPE_MODIFY = 10020;

    public static boolean haveDistrict = false; //是否有地区数据

    private int enterType; // 界面的类型 （新增或修改）
    private String addrId;
    private WaitingDialog dialog;

    @Override
    protected String activityDesc() {
        return getString(R.string.page_create_addr);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_addr);
        ButterKnife.bind(this);

        initData();
        initView();
    }

    /**
     * init data
     */
    private void initData() {

        enterType = getIntent().getIntExtra(EDIT_ADDR_TYPE, TYPE_CREAT);

        // ### 拿取编辑地址的数据 ###
        AddrInfoNetBean bean = getIntent().getParcelableExtra(AddrItemAdapter.ADDRBEAN);
        if (enterType == TYPE_MODIFY) {
            if (bean != null) {
                etReceiver.setText(bean.getUserName());
                etPhone.setText(bean.getPhone());
                cbDefault.setChecked(bean.getIsTactly().
                        equals(Constants.KEY_YES));

                String detailAddress = bean.getDetailAddress();
                String detailAddr = detailAddress.replace("&", "");
                int surplusLen = bean.getSurplusAddress().length();
                int detailLen = bean.getDetailAddress().length();
                // 截取地区地址
                String substring = detailAddr.substring(
                        0, detailLen - surplusLen);
                tvDistrictName.setText(substring);
                etSurplusAddr.setText(bean.getSurplusAddress());

                String postalCode = bean.getPostalCode();
                etPostcode.setText(postalCode);

                // 如果是-1让它报错（必然）
                position = getIntent().getIntExtra(
                        AddrItemAdapter.POSITION, -1);

                addrId = bean.getAddressId();
            }
        } else if (enterType == TYPE_CREAT) {
            addrId = "";
        }

        loadDistrictData();
    }

    /**
     * 加载assets中的三级地区数据（通过输入输出流）
     */
    private void loadDistrictData() {
        // ### 加载三级地区数据 ###
        InputStreamReader inputStreamReader;
        try {
            inputStreamReader = new InputStreamReader(getAssets().open(
                    ADDR_JSON), "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            inputStreamReader.close();
            bufferedReader.close();

            String json = stringBuilder.toString();
            Gson gson = new Gson();
            districtDatas = gson.fromJson(json, new
                    TypeToken<List<AddrUltimateBean>>() {
                    }.getType());
            if (districtDatas.size() > 0) {
                String areaName = districtDatas.get(0).getAreaName();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * init view
     */
    private void initView() {
        tvSave.setVisibility(View.VISIBLE);
        tabTvTitle.setText(R.string.title_edit_addr);
        rlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        cbDefault.setOnCheckedChangeListener(new CompoundButton
                .OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isDefault = isChecked;
            }
        });

        tvSave.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                if (checkInputEmpty()) {
                    return;
                }

                dialog = new WaitingDialog(CreateAddrActivity.this, "");
                dialog.setText(getString(R.string.saving));
                dialog.show();
                String districtName = PreferenceUtils.getString(CreateAddrActivity.this,
                        Constants.KEY_DISTRICT_NAME);

                String districtCode = PreferenceUtils.getString(CreateAddrActivity.this,
                        Constants.KEY_DISTRICT_CODE);

                if (districtName != null && districtCode != null) {
                } else {
                    return;
                }

                String[] districtNameArr = districtName.split("&");
                String[] districtCodeArr = districtCode.split("&");

//                AddrInfoBean bean = new AddrInfoBean(receiver, phone,
//                        NetConfig.currentEmpid, ,
//                        isDefault);
                // ### 如果是修改之前已有的地址 ###
//                if (isEdit) {
//                    editAddr(position, bean);
//                }
//                saveAddr(bean);
                String userName = etReceiver.getText().toString().trim();
                String phone = etPhone.getText().toString().trim();
                String surplusAddr = etSurplusAddr.getText().toString().trim();
                String district = tvDistrictName.getText().toString().trim();
                String postcode = etPostcode.getText().toString().trim();

                boolean isDefault = cbDefault.isChecked();
                String isTactly = (isDefault) ? Constants.KEY_YES : Constants
                        .KEY_NO;

                String districtAddr = districtName.replace("&", "");
                RequestUtils.saveOrUpdateAddress(addrId, userName, phone,
                        NetConfig.currentEmpid,
                        districtCodeArr[0], districtNameArr[0],
                        districtCodeArr[1], districtNameArr[1],
                        districtCodeArr[2], districtNameArr[2],
                        surplusAddr, districtAddr + surplusAddr, postcode,
                        isTactly, new RequestCallback() {
                            @Override
                            public void onError(Call call, Exception e) {
                                ToastUtils.toastContent(CreateAddrActivity.this,
                                        getString(R.string.chat_unconnect));
                                dialog.dismiss();
                            }

                            @Override
                            public void onResponse(ResponseBean responseBean) {
                                dialog.dismiss();
                                if (responseBean.getResultCode().equals(Constants.REQUEST_OK)) {
                                    Toast.makeText(CreateAddrActivity.this,
                                            R.string.tip_save_ok,
                                            Toast.LENGTH_SHORT).show();
                                    finish();
                                }
                            }
                        });
            }
        });

        llDistrictContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CreateAddrActivity.this,
                        DistrictStep1.class);
                intent.putParcelableArrayListExtra(DISTRICT_DATA,
                        districtDatas);
                startActivity(intent);
            }
        });
    }

    /**
     * 校验是否为空 如果不为空 设置这些数据给成员变量
     * @return true 为空  false 不为空
     */
    private boolean checkInputEmpty() {
        receiver = etReceiver.getText().toString().trim();
        if (TextUtils.isEmpty(receiver)) {
            Toast.makeText(CreateAddrActivity.this,
                    R.string.tip_name_empty,
                    Toast.LENGTH_SHORT).show();
            return true;
        }
        try {
            if (receiver.getBytes("utf-8").length > 20) {
                Toast.makeText(CreateAddrActivity.this, getString(R.string.tip_input_max),
                        Toast.LENGTH_SHORT).show();
                return true;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        phone = etPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(CreateAddrActivity.this,
                    R.string.tip_phone_empty,
                    Toast.LENGTH_SHORT).show();
            return true;
        }
        districtName1 = tvDistrictName.getText().toString()
                .trim();
        if (TextUtils.isEmpty(districtName1)) {
            Toast.makeText(CreateAddrActivity.this,
                    R.string.tip_district_empty,
                    Toast.LENGTH_SHORT).show();
            return true;
        }

        String postalCode = etPostcode.getText().toString().trim();
        if (TextUtils.isEmpty(postalCode)) {
            Toast.makeText(CreateAddrActivity.this, R.string.tip_postalcode_empty,
                    Toast.LENGTH_SHORT).show();
            return true;
        }

        surplusAddr = etSurplusAddr.getText().toString().trim();
        if (TextUtils.isEmpty(surplusAddr)) {
            Toast.makeText(CreateAddrActivity.this,
                    R.string.x_surplus_addr_empty,
                    Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();

//        // ### 回显 ###
//        // addr info bean
//        String json = PreferenceUtils.getString(this, Constants
//                .KEY_ADDR_INFO_BEAN);
//        Gson gson = new Gson();
//        AddrInfoBean bean = gson.fromJson(json, AddrInfoBean.class);
//
//        if (bean != null) {
//            etReceiver.setText(bean.getUserName());
//            etPhone.setText(bean.getPhone());
//            etSurplusAddr.setText(bean.getSurplusAddress());
//            cbDefault.setChecked(bean.getIsTactly().equals(Constants
// .KEY_YES));
//        }

        // 地区名
        if (haveDistrict) {
            districtName = PreferenceUtils.getString(this, Constants
                    .KEY_DISTRICT_NAME);
            String replace = districtName.replace("&", "");
            tvDistrictName.setText(replace);
        }
    }

    /**
     * 修改sp中的地址数据 并保存
     * @param position 所修改数据的位置
     * @param bean 最终存储的数据
     * @return 是否修改成功
     */
    private boolean editAddr(int position, AddrInfoBean bean) {
        String json = PreferenceUtils.getString(this, Constants
                .JSON_ADDR_LIST, "");
        if (!TextUtils.isEmpty(json)) {
            Gson gson = new Gson();
            List<AddrInfoBean> mDatas = gson.fromJson(json, new
                    TypeToken<List<AddrInfoBean>>() {
                    }.getType());
            mDatas.remove(position);
            mDatas.add(position, bean);
            String data = gson.toJson(mDatas);
            PreferenceUtils.putString(this, Constants.JSON_ADDR_LIST, data);
            return true;
        }
        return false;
    }

    /**
     * 存储一条新的地址数据
     * @param bean 新的地址数据
     * @return 是否添加成功
     */
    private boolean saveAddr(AddrInfoBean bean) {
        String json = PreferenceUtils.getString(this, Constants
                .JSON_ADDR_LIST, "");
        if (!TextUtils.isEmpty(json)) {
            Gson gson = new Gson();
            List<AddrInfoBean> mDatas = gson.fromJson(json, new
                    TypeToken<List<AddrInfoBean>>() {
                    }.getType());
            mDatas.add(bean);
            String data = gson.toJson(mDatas);
            PreferenceUtils.putString(this, Constants.JSON_ADDR_LIST, data);
            return true;
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        haveDistrict = false;
    }
}
